﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Lifebucket.Web.ViewModels;
using Lifebucket.Domain.Commands;
using Lifebucket.Core.Common;
using Lifebucket.Web.Core.Extensions;
using Lifebucket.CommandProcessor.Dispatcher;
using Lifebucket.Data.Repositories;
using Lifebucket.Web.Core.ActionFilters;
using AutoMapper;
using Lifebucket.Model;
namespace Lifebucket.Web.Controllers
{
    [CompressResponse]
    public class BucketItemController : Controller
    {
        private readonly ICommandBus commandBus;
        private readonly IBucketItemRepository bucketItemRepository;
        public BucketItemController(ICommandBus commandBus, IBucketItemRepository bucketItemRepository)
        {
            this.commandBus = commandBus;
            this.bucketItemRepository = bucketItemRepository;
        }

        public ActionResult Index()
        {
            var categories = bucketItemRepository.GetAll();
            return View(categories);
        }

        public ActionResult Details(int id)
        {
            return View();
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpGet]
        public ActionResult Edit(int id)
        {
            var bucketItem = bucketItemRepository.GetById(id);
            var viewModel = Mapper.Map<BucketItem, BucketItemFormModel>(bucketItem);
            return View(viewModel);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Save(BucketItemFormModel form)
        {
            if (ModelState.IsValid)
            {
                var command = Mapper.Map<BucketItemFormModel, CreateOrUpdateBucketItemCommand>(form);
                IEnumerable<ValidationResult> errors = commandBus.Validate(command);
                ModelState.AddModelErrors(errors);
                if (ModelState.IsValid)
                {
                    var result = commandBus.Submit(command);
                    if (result.Success) return RedirectToAction("Index");
                }
            }
            //if fail
            if (form.BucketItemId == 0)
                return View("Create", form);
            else
                return View("Edit", form);
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            var command = new DeleteBucketItemCommand { BucketItemId = id };
            var result = commandBus.Submit(command);
            var bucketItems = bucketItemRepository.GetAll();
            return PartialView("_BucketItemList", bucketItems);
        }
    }
}
